package com.itheima.web.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.domain.system.Module;
import com.itheima.domain.system.User;
import com.itheima.domain.system.UserPortrait;
import com.itheima.service.system.UserProtraitService;
import com.itheima.service.system.UserService;

import com.itheima.utils.FileUploadUtil;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.multipart.MultipartFile;

import java.util.*;


@Controller
public class LoginController extends BaseController {
    @Reference
    private UserProtraitService userProtraitService;
    @Reference
    private UserService userService;
    @Autowired
    private FileUploadUtil fileUploadUtil;


    //登录
    @RequestMapping("/login")
    public String login(String email, String password,String openid) {
        System.out.println(openid);
        if (password.length()!=32){
             password = new Md5Hash(password, email, 2).toString();
        }

        //1 将email和password 封装为Token
        if (userService.findByEmail(email)==null){
            User user = new User();
            user.setId(UUID.randomUUID().toString());
            user.setOpenid(openid);
            user.setUserName(UUID.randomUUID().toString());
            user.setPassword(password);
            user.setEmail(email);
            userService.save(user);
        }
        if (userService.findByOpenid(openid)==null){
            User user = userService.findByEmail(email);
            user.setOpenid(openid);
            userService.update(user);
        }

        AuthenticationToken authenticationToken = new UsernamePasswordToken(email, password);

        //2 调用Subject的login登录
        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(authenticationToken);

            //3 获取登录结果
            User user = (User) subject.getPrincipal();

            //4 登录成功之后要处理的事情
            session.setAttribute("loginUser", user);
            List<Module> moduleList = userService.findModuleByUser(user);
            if (userProtraitService.selectByPrimaryKey(user.getId()) != null) {
                UserPortrait userPortraits = userProtraitService.selectByPrimaryKey(user.getId());
                if (userPortraits != null) {
                    String userProtrait = userPortraits.getUserProtrait();
                    session.setAttribute("userProtrait", userProtrait);
                }
            }
            session.setAttribute("modules", moduleList);
            return "redirect:/home/main.do";

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "用户名或者密码错误");
            return "forward:/login.jsp";
        }
    }
    //主页面
    @RequestMapping("/home/main")
    public String main() {
        return "home/main";
    }

    @RequestMapping("/home/home")
    public String home() {
        return "home/home";
    }

    //退出
    @RequestMapping(value = "/logout", name = "用户注销")
    public String logout() {
        SecurityUtils.getSubject().logout();   //登出
        return "redirect:/login.jsp";
    }


    @RequestMapping(value = "/checkUser", name = "跳转到个人信息修改页面")
    public String checkUser() {
        User user = userService.findById(getLoginUser().getId());
        //密码不回显
        user.setPassword(null);
        request.setAttribute("user", user);
        //用户修改时的跳转页面
        return "system/user/user-change";
    }

    @RequestMapping(value = "/changeUser", name = "修改个人信息")
    public String changeUser(User user, UserPortrait userPortrait, MultipartFile file) {
        try {
            if (!file.isEmpty()) {
                //七牛云回来的地址
                String imgpath = fileUploadUtil.upload(file);
                //先存到session中
                session.setAttribute("userPortrait", imgpath);
                //判断数据库中是否有地址  没有 添加   有 则修改
                //存到数据库的地址
                if (userProtraitService.selectByPrimaryKey(user.getId()) == null) {
                    userPortrait.setUserId(user.getId());
                    userPortrait.setUserProtrait(imgpath);
                    //头像回显
                    userProtraitService.insert(userPortrait);
                } else {
                    userProtraitService.deleteByPrimaryKey(user.getId());
                    userPortrait.setUserId(user.getId());
                    userPortrait.setUserProtrait(imgpath);
                    userProtraitService.insert(userPortrait);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        User loginUser = (User) session.getAttribute("loginUser");
        String passwordOld = loginUser.getPassword();
        loginUser.setBirthday(user.getBirthday());
        loginUser.setTelephone(user.getTelephone());
        loginUser.setGender(user.getGender());
        loginUser.setUserName(user.getUserName());
        loginUser.setId(user.getId());
        userService.update(loginUser);
        //1.获取新上传的的密码()
        //2.判断前台传来的密码是否为null
        //3. null则 密码没变,将就密码保存 并且判断用户信箱是否改变   改变则上传新信箱
        //4.不是null
        if (StringUtils.isNotEmpty(user.getPassword())) {
            String passwordNew = new Md5Hash(user.getPassword(), user.getEmail(), 2).toString();
            user.setPassword(passwordNew);
            userService.update(user);
            return "redirect:/logout.do";
        } else {//当密码没变时
            //判断邮箱是否改变    不改变则添加用户返回带主页面    改变则跳转到登录页面
            if (user.getEmail().equals(loginUser.getEmail())) {
                user.setPassword(passwordOld);
                userService.update(user);
                return "redirect:/home/main.do";
            } else {
                user.setPassword(passwordOld);
                userService.update(user);
                return "redirect:/logout.do";
            }
        }
    }

    //通过微信code登录
    @RequestMapping(value = "/weixinlogin")
    public String wxLogin(String code) {

        User user = userService.wxLogin(code);
        if (user==null){
            request.setAttribute("ss","请注册");
            return "forward:/login.jsp";
        }
        if (user.getEmail()==null){
            request.setAttribute("ss","请绑定账户");
            request.setAttribute("user",user);
            return "forward:/login.jsp";
        }else {
            return "forward:/login.do?email="+user.getEmail()+"&password="+user.getPassword()+"&openid="+user.getOpenid();
        }
    }
}

